package com.itqf;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple Quickstart application showing how to use Shiro's API.
 *
 * @since 0.9 RC2
 */

public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        //SecurityManager  shiro核心组件  realm  subject
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        //设置安全管理对象
        SecurityUtils.setSecurityManager(securityManager);

        // get the currently executing user:
        //subject  --》当前用户
        Subject currentUser = SecurityUtils.getSubject();

//        // Do some stuff with a Session (no need for a web or EJB container!!!)
//        Session session = currentUser.getSession();
//        session.setAttribute("someKey", "aValue");

 //       String value = (String) session.getAttribute("someKey");

        // let's login the current user so we can check against roles and permissions:
        //判断用户是否 认证（登录）
        if (!currentUser.isAuthenticated()) {

            UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "admin");
            token.setRememberMe(true);//记住我
            try {
                currentUser.login(token);

                System.err.println(currentUser.isAuthenticated()?"success":"fail");

            } catch (UnknownAccountException uae) {
                log.info("用户名错误");
            } catch (IncorrectCredentialsException ice) {
                log.info("密码错误");
            } catch (LockedAccountException lae) {
                log.info("账户被锁定");
            }
            catch (AuthenticationException ae) {
                log.info("other");
            }
        }
        //zhangsan = admin, test
        //判断具有某个角色
        System.out.println(currentUser.hasRole("test")?"具有test角色":"不具有test角色");

        System.out.println(currentUser.hasRole("admin")?"具有admin角色":"不具有admin角色");

        //权限
        //test = sys:product:*
        System.out.println(currentUser.isPermitted("sys:product:find")?"具有find商品权限":"不具有find商品权限");
        System.out.println(currentUser.isPermitted("sys:product:add")?"具有add商品权限":"不具有add商品权限");
        System.out.println(currentUser.isPermitted("sys:product:update")?"具有update商品权限":"不具有update商品权限");
        System.out.println(currentUser.isPermitted("sys:order:find")?"具有find订单权限":"不具有find订单权限");


        if (currentUser.hasRole("test")){
            //业务逻辑
        }


    }
}
